<template>
	<view>
		<view class="card p-0-20">
			<view class="item d-flex a-center" v-if="processInstanceId">
				<view class="size28 color-222">任务类型：</view>
				<input class="flex-1 text-right size28" v-model="processName" disabled />
			</view>
			<view class="item d-flex a-center" @click="showAction = true" v-else>
				<!-- <text class="iconfont icon-bitian size24 color-e81"></text> -->
				<view class="size28 color-222">任务类型：</view>
				<input class="flex-1 text-right size28" v-model="processName" placeholder="请选择" disabled />
				<text class="iconfont icon-a-zujian32 size24 color-999 m-left20"></text>
			</view>
			<block v-for="(item,index) in formList" :key="index">
				<!-- 单行输入框 -->
				<view class="item d-flex a-center" v-if="item.fieldType == 'input'">
					<!-- <text class="iconfont icon-bitian size24" :class="item.required == 1 ? 'color-e81' : 'white'"></text> -->
					<view class="size28 color-222">{{ item.title }}：</view>
					<input class="flex-1 text-right size28" v-model="item.value" :placeholder="item.placeholder" />
				</view>
				<!-- 数字输入框 -->
				<view class="item d-flex a-center" v-if="item.fieldType == 'number'">
					<view class="size28 color-222">{{ item.title }}：</view>
					<input class="flex-1 text-right size28" type="digit" v-model="item.value" :placeholder="item.placeholder" />
				</view>
				<!-- 文本域 -->
				<view class="item" v-if="item.fieldType == 'textarea'">
					<text class="size28 color-222">{{ item.title }}：</text>
					<up-textarea v-model="item.value" :placeholder="item.placeholder" placeholderClass="size28" count maxlength="150" border="none"></up-textarea>
				</view>
				<!-- 选择器 -->
				<view class="item d-flex a-center" @click="openPicker(item, index)" v-if="item.fieldType == 'post'">
					<view class="size28 color-222">{{ item.title }}：</view>
					<input class="flex-1 text-right size28" v-model="item.label" :placeholder="item.placeholder" disabled />
					<text class="iconfont icon-a-zujian32 size24 color-999 m-left20"></text>
				</view>
				<!-- 日期时间 -->
				<view class="item d-flex a-center" @click="openDatetimePicker(item, index)" v-if="item.fieldType == 'date' || item.fieldType == 'datetime'">
					<view class="size28 color-222">{{ item.title }}：</view>
					<input class="flex-1 text-right size28" v-model="item.value" :placeholder="item.placeholder" disabled />
					<text class="iconfont icon-a-zujian32 size24 color-999 m-left20"></text>
				</view>
				<!-- 附件 -->
				<view class="item" v-if="item.fieldType == 'file'">
					<choose-file :title="item.title" :rawFile="item.value" :current="index" @getFile="getFile" />
				</view>
			</block>
        </view>
        <view class="card padding30">
            <view class="size30 color-222 bold m-bot40">审批流程：</view>
            <view class="step d-flex a-center" v-for="(item,index) in tasks" :key="index">
                <view class="dot m-right26"></view>
                <view class="flex-1 size28 color-222">{{ item.taskInfo.name }}</view>
                <view class="size24 color-666 m-right20">{{ item.auditUserInfo[0].userName }}</view>
                <image class="avatar" :src="item.auditUserInfo[0].avatar ? imgUrls(item.auditUserInfo[0].avatar) : staticImg + 'noExist.jpg'" mode="aspectFill"></image>
            </view>
        </view>
        <view class="btn flexac size28 white" @click="submit">提交</view>

		<!-- 操作菜单-选择任务类型 -->
		<up-action-sheet :show="showAction" :actions="taskType" closeOnClickOverlay @close="showAction = false" @select="selectType"></up-action-sheet>
        <!-- 选择器 -->
		<up-picker :show="showPicker" :columns="columns" :keyName="keyName" :loading="loading" @cancel="showPicker = false" @confirm="confirmPicker"></up-picker>
		<!-- 日期时间 -->
		<up-datetime-picker :show="showDatetimePicker" v-model="datetime" :mode="mode" @cancel="showDatetimePicker = false" @confirm="confirmDatetime"></up-datetime-picker>
	</view>
</template>

<script setup>
    import { ref, onMounted } from 'vue'
	import { useMainStore } from '@/stores/index'
	import { staticImg } from '@/utils/config.js'
    import { toUrl, Toast, imgUrls, Back, showLoading, hideLoading, Modal } from '@/utils/utils.js'
    import Http from '@/utils/request.js'
	import chooseFile from '../../components/chooseFile.vue'

	const mainStore = useMainStore()
	const props = defineProps({
		defaultType: { // 默认流程类型
			type: String,
			default: ''
		},
		defaultValue: { // 用来回显的json对象
			type: String,
			default: ''
		},
		processInstanceId: {
			type: String,
			default: ''
		}
	})

	onMounted(() => {
		processType.value = props.defaultType
		getDepts()
		if (props.processInstanceId) {
			getDetail()
		} else {
			getType()
			if(processType.value) getForm()
		}
	})

    const formList = ref([]) // 表单数据
	const tasks = ref([]) // 审批流程

	const getForm = (payload = '') => {
		Http.get({
			url: '/hr/process/findFormInfo',
			data: {
				processType: payload.processType || processType.value
			}
		}).then(res => {
			if(res.code != 0) return Modal(res.msg, '提示', false)
			let result = res.data || ''
			formList.value = result.formInfoList || []
			tasks.value = result.tasks || []
			// 切换流程类型
			if(payload) {
				processType.value = payload.processType
				processName.value = payload.name
			}
			// 路由传参回显
			if(props.defaultValue && processType.value == props.defaultType) {
				let keys = Object.keys(JSON.parse(props.defaultValue)) // fieldName数组
				formList.value.forEach(item => {
					if(keys.includes(item.fieldName)) {
						// 根据fieldName判断是部门
						if(item.fieldName == 'currentDept' || item.fieldName == 'targetDept') {
							let deptName = JSON.parse(props.defaultValue)[item.fieldName]
							let obj = deptList.value.find(item => item.deptName == deptName)
							if(obj) {
								item.label = deptName
								item.value = obj.deptId
							}
						// 离职-交接人
						} else if(item.fieldName == 'transitionUser') {
							let name = JSON.parse(props.defaultValue)[item.fieldName]
							findUser({name}).then(user => {
								if(!user) return
								item.label = name
								item.value = user.userId
							})
						} else {
							item.value = JSON.parse(props.defaultValue)[item.fieldName]
						}
					}
				})
			}
		})
	}

	const getDetail = () => {
		Http.get({
			url: '/hr/process/findDetail',
			data: {
				processInstanceId: props.processInstanceId
			}
		}).then(res => {
			if(res.code != 0) return Modal(res.msg, '提示', false)
			let result = res.data
			if(!result) return
			formList.value = result.processFormFieldInfos || []
			tasks.value = result.tasks || []
			processName.value = result.process.processName
			// 特殊处理
			formList.value.forEach(item => {
				if(item.postType == 'department') {
					let obj = deptList.value.find(dept => dept.deptId == item.value)
					if(obj) item.label = obj.deptName
				}
			})
		})
	}

    const submit = () => {
        console.log(formList.value)
		let result = formList.value.find(item => item.required == 1 && (!item.value || !item.value.length))
		if (result) return Toast(result.title + '不能为空')
        let params = {}
        formList.value.forEach(item => {
            params[item.fieldName] = item.value
        })
        console.log(params)
		showLoading()

		// 修改流程数据
		if(props.processInstanceId) {
			Http.post({
				url: '/hr/process/updateProcessData',
				data: {
					processInstanceId: props.processInstanceId,
					processData: JSON.stringify(params)
				}
			}).then(res => {
				hideLoading()
				if(res.code != 0) return Modal(res.msg, '提示', false)
				handleAudit()
			})
			return
		}

		// 发起申请
		Http.post({
			url: '/hr/process/startProcess',
			data: {
				processType: processType.value,
				processName: processName.value,
				processData: JSON.stringify(params)
			}
		}).then(res => {
			hideLoading()
			if(res.code != 0) return Modal(res.msg, '提示', false)
			Toast(res.msg)
			setTimeout(() => {
				Back()
			}, 1500)
		})
    }

	// 申请人修改后提交给下个节点
	const handleAudit = () => {
		Http.post({
			url: '/hr/process/audit',
			data: {
				processInstanceId: props.processInstanceId,
				auditUserId: mainStore.userInfo.userId,
				auditUserName: mainStore.userInfo.userName,
				isPass: true
			}
		}).then(res => {
			if(res.code != 0) return Modal(res.msg, '提示', false)
			Toast(res.msg)
			setTimeout(() => {
				Back()
			}, 1500)
		})
	}

	// 操作菜单
	const showAction = ref(false)
	const processType = ref('') // 流程类型
	const processName = ref('') // 流程名称
	const taskType = ref([])
	const getType = () => {
		Http.get({
			url: '/hr/process/queryMyProcess'
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			let result = res.data || []
			taskType.value = result.map(item => ({...item, name: item.processName}))
			if(!taskType.value.length) return
			if(props.defaultType) {
				let result = taskType.value.find(item => item.processType == props.defaultType)
				if(result) processName.value = result.name
				return
			}
			processType.value = taskType.value[0].processType
			processName.value = taskType.value[0].processName
			getForm()
		})
	}
	const selectType = (item) => {
		if(processType.value == item.processType) return
		getForm(item)
	}

	// 部门
	const deptList = ref([])
	const getDepts = () => {
		Http.get({
			url: '/hr/getDeptList'
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			deptList.value = res.data || []
		})
	}

	const Obj = ref('') // 当前表单项
	const current = ref(0) // 下标

    // 选择器
	const showPicker = ref(false)
	const columns = ref([[]])
	const keyName = ref('')
	const loading = ref(false)
	const openPicker = (item, index) => {
		Obj.value = item
		current.value = index
		// 部门
		if(item.postType == 'department') {
			keyName.value = 'deptName'
			columns.value[0] = deptList.value
			showPicker.value = true
		}
		// 返回会触发publish页面的onShow并调用process组件的pageShow
		if(item.postType == 'user') toUrl('/bizPage/task/selectList')
	}
	const confirmPicker = (e) => {
		console.log('e', e.value)
		if(Obj.value.postType == 'department') {
			formList.value[current.value].label = e.value[0].deptName
			formList.value[current.value].value = e.value[0].deptId
		}
		showPicker.value = false
	}

	// 查询员工信息
	const findUser = ({userId = '', name = ''}) => {
		return new Promise(resolve => {
			Http.get({
				url: '/hr/process/findEmployeeInfoByUserId',
				data: {
					userId,
					name
				}
			}).then(res => {
				if(res.code != 0) return Toast(res.msg)
				resolve(res.data)
			})
		})
	}

	const pageShow = (userId) => {
		if(Obj.value.postType == 'user') {
			formList.value[current.value].value = userId
			findUser({userId}).then(user => {
				if(user) formList.value[current.value].label = user.name
			})
		}
	}

	defineExpose({
		pageShow
	})
	
	// 日期时间
	const showDatetimePicker = ref(false)
	const mode = ref('datetime') // date日期(年月日)、time时间、year-month年月
	const datetime = ref(Date.now())
	const openDatetimePicker = (item, index) => {
		Obj.value = item
		current.value = index
		mode.value = item.fieldType
		if(item.value) {
			let val = item.value.replace(/-/g, '/') // 兼容ios
			datetime.value = new Date(val).getTime()
		}
		showDatetimePicker.value = true
	}
	const confirmDatetime = (e) => {
		console.log('时间戳', e)
		let format = 'yyyy-mm-dd hh:MM'
		if(mode.value == 'date') format = 'yyyy-mm-dd'
		if(mode.value == 'time') format = 'hh:MM'
		if(mode.value == 'year-month') format = 'yyyy-mm'
		formList.value[current.value].value = uni.$u.timeFormat(e.value, format)
		showDatetimePicker.value = false
	}

	// 附件
	const getFile = ({file, index}) => {
		formList.value[index].value = file
	}
</script>

<style lang="scss" scoped>
	.card {
		background: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		&.p-0-20 {
			padding: 0 20rpx;
		}
		.item {
			padding: 30rpx 0;
			&:not(:last-child) {
				border-bottom: 1rpx solid #F2F2F2;
			}
		}
	}
    .step:not(:last-child) {
		margin-bottom: 60rpx;
		position: relative;
		&::after {
			content: '';
			width: 1rpx;
			height: 80rpx;
			background: #CDCDCD;
			position: absolute;
			left: 5rpx;
			transform: translateX(-50%);
			bottom: -70rpx;
		}
	}
    .dot {
		width: 10rpx;
		height: 10rpx;
		background: #CDCDCD;
		border-radius: 50%;
	}
    .avatar {
		width: 66rpx;
		height: 66rpx;
		border-radius: 10rpx;
	}
    .btn {
		width: 690rpx;
		height: 82rpx;
		background: #0B77F0;
		border-radius: 20rpx;
		margin: 60rpx auto;
	}
</style>